package com.gin.kotlin.vegetables_kot.base

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.widget.Toast
import java.lang.ref.WeakReference

/**
 *
 * @param context 持有该Handler的上下文
 * @param callback 处理消息的回调
 * @constructor
 */
class MyHandler(context: Context, private val callback: Callback) : Handler(Looper.myLooper()!!, callback) {
    private val weakReference: WeakReference<Context> = WeakReference(context)

    @Suppress("PrivatePropertyName")
    private val TAG = context.javaClass.simpleName

    /**
     * 处理消息
     * @param msg Message
     */
    override fun handleMessage(msg: Message) {
        obtainContext("handleMessage", "消息未处理, what: ${msg.what} arg1: ${msg.arg1} arg2: ${msg.arg2}") ?: return
        callback.handleMessage(msg)
        Log.i(TAG, "handleMessage: 消息已处理, what: ${msg.what} arg1: ${msg.arg1} arg2: ${msg.arg2}")
    }

    /**
     * 发送消息，将枚举类的ordinal字段作为what属性
     * @param what 某个枚举类对象
     * @param payload 消息载荷
     * @return Boolean
     */
    fun <T : Enum<*>> sendMessage(what: T, payload: Any? = null) = sendMessage(obtainMessage(what.ordinal, payload))
    fun <T : Enum<*>> sendMessage(what: T, arg1: Int = 0, arg2: Int = 0) = sendMessage(obtainMessage(what.ordinal, arg1, arg2))

    /**
     * 发送消息，将枚举类的ordinal字段作为what属性
     * @param what 某个枚举类对象
     * @return Boolean
     */
    fun <T : Enum<*>> sendEmptyMessage(what: T) = sendEmptyMessage(what.ordinal)

    /**
     * 发送一条toast短消息
     * @param message String
     */
    fun toast(message: String?) {
        if (message!=null) {
            val context = obtainContext("toast", "提示未发送 - $message") ?: return
            Log.d(TAG, "[Toast] 消息已发送: $message")
            post { Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }
        }else{
            Log.w(TAG, "[Toast] 消息未发送: message为null", )
        }
    }

    /**
     * 发送一条toast长消息
     * @param message String
     */
    fun toastLong(message: String) {
        val context = obtainContext("toastLong", "提示未发送 - $message") ?: return
        Log.d(TAG, "toastLong: 消息已发送: $message")
        post { Toast.makeText(context, message, Toast.LENGTH_LONG).show() }
    }

    /**
     * 发送一条功能开发中的报错
     */
    fun toastDevInProgress() = toast("功能开发中...")

    /**
     * 在Activity / Fragment的 onDestroy 方法中执行
     */
    fun onDestroy() {
        // 清空正在执行的任务
        removeCallbacksAndMessages(null)
    }

    private fun obtainContext(methodName: String, failedMessage: String): Context? {
        val context = weakReference.get()
        if (context == null) {
            Log.w(TAG, "$methodName: 上下文已注销, 操作失败")
            Log.w(TAG, "$methodName: $failedMessage")
        }
        return context
    }

    companion object {

    }
}